using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;

namespace PresentItNow
{
    

    public class CursorHelper
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern bool SetCursorPos(int X, int Y);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern bool GetCursorPos(ref System.Drawing.Point lpPoint);


        private static Point GetResolution(Visual visual)
        {
            //This is a bit tricky, because we might not be on Vista - and have to calculate the mouse position on our own
            Point dpi = new Point(120, 120);

            PresentationSource source = PresentationSource.FromVisual(visual);
            if (source == null)
                return dpi;

            CompositionTarget target = source.CompositionTarget;

            Matrix m = target.TransformToDevice;
            MatrixTransform t = new MatrixTransform(m);

            Point pt1 = new Point(0, 0);
            pt1 = t.Transform(pt1);

            Point pt2 = new Point(96, 96);
            pt2 = t.Transform(pt2);

            dpi.X = pt2.X - pt1.X;
            dpi.Y = pt2.Y - pt1.Y;
            return dpi;
        }

        public static Point GetCursorPos(Visual currentVisual)
        {
            CursorHelper.currentVisual = currentVisual;
            System.Drawing.Point absPoint = new System.Drawing.Point() ;
            GetCursorPos(ref absPoint);

            double X = absPoint.X * 96 / Resolution.X;
            double Y = absPoint.Y * 96 / Resolution.Y;

            return new Point(X, Y);
        }

        private static Visual currentVisual = null;

        private static bool isGotResolution = false;
        private static Point resolution;        
        private static Point Resolution
        {
            get
            {
                if (!isGotResolution)
                {
                    resolution = GetResolution(currentVisual);
                    isGotResolution = true;
                }
                return resolution;
            }
        }
    }
}
